package com.example.shellcollector;

import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.StatFs;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.transition.TransitionInflater;

import com.example.shellcollector.Entity.InstalledAppUsage;
import com.example.shellcollector.MyAnimate.MyCountAdapter;
import com.example.shellcollector.MyAnimate.MyProgressBar;
import com.example.shellcollector.MyAnimate.MyRecycleAdapter;
import com.example.shellcollector.database.InstalledAppUsageDao;
import com.example.shellcollector.database.ShellCollectorDatabase;

import com.example.shellcollector.ShowApp.ShowAppDetails;


import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executor;


public class HomeFragment extends Fragment {
    static final String TAG = "HomeFragmentTag";
    private String storageUsed;
    private String storageTotal;
    private float storagePer;
    private MyProgressBar batteryBar;
    private MyProgressBar storageBar;
    private List<InstalledAppUsage> appUnused = null;
    private List<InstalledAppUsage> appCount = null;
    private Timer timer;

    private  MyTask myTask1;
    private  MyTask myTask2;

    private InstalledAppUsageDao installedAppUsageDao;

    @Override
    public void onDestroyView() {
        super.onDestroyView();

        if (!myTask2.isCancelled()) {
            myTask2.cancel(true);
            timer.cancel();
        }

        if (!myTask1.isCancelled()) {
            myTask1.cancel(true);
            timer.cancel();
        }

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TransitionInflater inflater = TransitionInflater.from(requireContext());
        setEnterTransition(inflater.inflateTransition(R.transition.fade));
        setExitTransition(inflater.inflateTransition(R.transition.fade));
        getStorageInfo(getContext());


        installedAppUsageDao = ShellCollectorDatabase.getDatabase(getContext()).getInstalledAppUsageDao();

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_home, container, false);

        TextView batteryText = (TextView) v.findViewById(R.id.battery2);
        batteryText.setText(getBatteryLevel() + " " + "%");

        TextView used = (TextView) v.findViewById(R.id.storage_used);
        TextView total = (TextView) v.findViewById(R.id.storage_total);
        used.setText("已使用" + storageUsed);
        total.setText("总计" + storageTotal + " · 内部存储空间");


        storageBar = (MyProgressBar) v.findViewById(R.id.storageBar);
        storageBar.setColor(0xFF004AA0);
        storageBar.setProgress((int) (storagePer * 100), 100);

        batteryBar = (MyProgressBar) v.findViewById(R.id.bprocessbar);
        batteryBar.setProgress(getBatteryLevel(), 100);


        myTask2 = new MyTask();
        myTask1 = new MyTask();
        HashMap<Integer, View> map2 = new HashMap<>();
        map2.put(2, v);
        if (myTask2.getStatus() != AsyncTask.Status.RUNNING)
            myTask2.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, map2);


        TimerTask task = new TimerTask() {
            public void run() {
                HashMap<Integer, View> map1 = new HashMap<>();
                map1.put(1, v);
                if (myTask1.getStatus() != AsyncTask.Status.RUNNING)

                    myTask1.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, map1);
            }
        };
        timer = new Timer();
        timer.schedule(task, 1500);


        return v;
    }

    private class MyTask extends AsyncTask<HashMap<Integer, View>, Integer, HashMap<Integer, View>> {
        private ProgressBar p1;
        private ProgressBar p2;
        private int flag = 0;
        private View v;

        @Override
        protected void onPreExecute() {
            // 执行前显示提示
        }

        @Override
        protected HashMap<Integer, View> doInBackground(HashMap<Integer, View>... params) {

            if (params[0].containsKey(1)) {
                appUnused = getAppUnused();
                v = params[0].get(1);
                flag = 1;
                int count = 0;
                while (count < 100) {
                    publishProgress(count);
                    count++;
                }
                return params[0];
            } else {
                appCount = getUsedCount();
                v = params[0].get(2);
                flag = 2;
                int count = 0;
                while (count < 100) {
                    publishProgress(count);
                    count++;
                }
                return params[0];
            }
        }

        @Override
        protected void onProgressUpdate(Integer... progresses) {
            if (flag == 1) {
                p1 = v.findViewById(R.id.progressBar1);
                p1.setProgress(progresses[0]);
            } else {
                p2 = v.findViewById(R.id.progressBar2);
                p2.setProgress(progresses[0]);
            }
        }

        @Override
        protected void onPostExecute(HashMap<Integer, View> map) {
            // 执行完毕后，则更新UI
            if (map.containsKey(1)) {
                setAppUnused(map.get(1));
                p1.setVisibility(View.INVISIBLE);
            } else {
                setAppCount(map.get(2));
                p2.setVisibility(View.INVISIBLE);
            }
        }

    }


    // 计算剩余电量
    private int getBatteryLevel() {
        BatteryManager manager = (BatteryManager) getContext().getSystemService(Context.BATTERY_SERVICE);
        return manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
    }

    // 计算存储空间信息
    private void getStorageInfo(Context context) {
        StatFs fs = new StatFs(Environment.getDataDirectory().getAbsolutePath());
        long blockCountLong = fs.getBlockCountLong();
        long availableBlocksLong = fs.getAvailableBlocksLong();
        long blockSizeLong = fs.getBlockSizeLong();
        long totalSize = blockSizeLong * blockCountLong;
        long usedSize = totalSize - availableBlocksLong * blockSizeLong;
        storagePer = (float) usedSize / totalSize;
        System.out.println("总：" + totalSize + "用：" + usedSize + "占：" + storagePer);
        storageTotal = Formatter.formatFileSize(context, totalSize);
        storageUsed = Formatter.formatFileSize(context, usedSize);
    }

    private List<InstalledAppUsage> getAppUnused() {
        Calendar calendar = Calendar.getInstance();
        long endt = calendar.getTimeInMillis();
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        long statt = calendar.getTimeInMillis();

        UsageStatsManager usageStatsManager = getContext().getSystemService(UsageStatsManager.class);
        List<UsageStats> usageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_MONTHLY, statt, endt);

        List<InstalledAppUsage> appUnused = new ArrayList<>();
        System.out.println("***********************\n" + usageStats.size());

        HashMap<String, UsageStats> map = new HashMap<>();

        PackageManager pm = getContext().getPackageManager();
        Calendar call1 = Calendar.getInstance();
        Calendar call2 = Calendar.getInstance();

        for (UsageStats entity : usageStats) {

            ApplicationInfo info = null;

            try {
                // System.out.println(entity.getPackageName());
                info = pm.getApplicationInfo(entity.getPackageName(), 0);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            if (info == null)
                continue;
            if ((ApplicationInfo.FLAG_SYSTEM & info.flags) != 0) {
                continue;
            }

            call1.setTimeInMillis(entity.getLastTimeUsed());
            call2.setTimeInMillis(System.currentTimeMillis());


            int day1 = call1.get(Calendar.DAY_OF_YEAR);

            int day2 = call2.get(Calendar.DAY_OF_YEAR);

            int year1 = call1.get(Calendar.YEAR);
            int year2 = call2.get(Calendar.YEAR);

//            System.out.println("***********\nday1:" + day1 + "    year1:" + year1);
//            System.out.println("***********\nday2:" + day2 + "    year2:" + year2);
            int timeInterval = 0;

            if (year1 != year2) {
                int timeDistance = 0;
                for (int i = year1; i < year2; i++) {
                    if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
                        timeDistance += 366;
                    } else {
                        timeDistance += 365;
                    }
                }
                timeInterval = day2 - day1 + timeDistance;
            } else
                timeInterval = day2 - day1;

            if (timeInterval > 30) {
                // 如果相隔大于30天，加入到列表中
                InstalledAppUsage installedAppUsage = new InstalledAppUsage();

                installedAppUsage.setAppName(info.loadLabel(pm).toString());
                installedAppUsage.setAppPackageName(entity.getPackageName());
                appUnused.add(installedAppUsage);
            }
        }

        return appUnused;
    }

    // 设置
    private void setAppUnused(View v) {
        RecyclerView recyclerView = v.findViewById(R.id.recycleView);
        recyclerView.setVisibility(View.VISIBLE);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);

        layoutManager.setOrientation(RecyclerView.HORIZONTAL);

        MyRecycleAdapter adapter = new MyRecycleAdapter(appUnused, getContext().getPackageManager());

        recyclerView.setAdapter(adapter);
        LayoutAnimationController animationController = AnimationUtils.loadLayoutAnimation(getContext(), R.anim.layout_animation_to_left);
        recyclerView.setLayoutAnimation(animationController);

        adapter.setOnItemClickListener(new MyRecycleAdapter.ItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent();
                intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                intent.setData(Uri.fromParts("package", appUnused.get(position).getAppPackageName(), null));
                getContext().startActivity(intent);
            }
        });
    }

    private void setAppCount(View v) {
        RecyclerView recyclerView = v.findViewById(R.id.recycleAppcount);
        recyclerView.setVisibility(View.VISIBLE);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);

        MyCountAdapter adapter = new MyCountAdapter(appCount, getContext().getPackageManager());

        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new MyCountAdapter.ItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent(getContext(), ShowAppDetails.class);
                Bundle bundle = new Bundle();
                bundle.putParcelable("InstalledAppUsage", appCount.get(position));
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

    }

    // 使用频次排序
    private List<InstalledAppUsage> getUsedCount() {
        List<InstalledAppUsage> subList = new ArrayList<>();
        List<InstalledAppUsage> launchCounts = installedAppUsageDao.getAllOrderByLaunchCount(false);
        if (launchCounts.size() > 5) {
            subList = launchCounts.subList(0, 5);
        }
        return subList;
    }


}
